"""
@Author : DYC
@Date :  2025/6/7 15:07
@Description : 
用户自定义工具
"""
import hashlib, json
import datetime

import jwt
from django.http import HttpResponse

from role.models import Role
from dept.models import Department


# 自定义序列化器
def customer_serializable(obj):
    # 如果是date类型
    if isinstance(obj, datetime.date):
        # 格式化
        return obj.strftime('%Y-%m-%d')
    if isinstance(obj, Role):
        return {'id': obj.id, 'role_name': obj.role_name, 'role_en': obj.role_en, 'description': obj.description}
    if isinstance(obj, Department):
        return {'id': obj.id, 'dept_name': obj.dept_name, 'address': obj.address, 'create_time': obj.create_time}

    raise TypeError(f'Type {type(obj)} not serializable')

class CustomerUtils:

    """md5加密"""
    @staticmethod
    def md5(data:str):
        return hashlib.md5(data.encode('utf-8')).hexdigest()

    """创建token"""
    @staticmethod
    def create_token(payload:dict, secret:str):
        return jwt.encode(payload, secret, algorithm='HS256')


    """解析验证token"""
    @staticmethod
    def verify_token(token:str, secret:str):
        return jwt.decode(token, key=secret, algorithms=['HS256'])

    """返回HTTP响应"""
    @staticmethod
    def response_json(response_data):
        return HttpResponse(json.dumps(response_data, default=customer_serializable).encode('utf-8'), content_type='application/json;charset=UTF-8')

    """获取请求数据"""
    @staticmethod
    def get_request_data(request):
        user_form = json.loads(request.body.decode('utf-8'))
        return user_form